package service

import (
	"go_web/config"
	"go_web/dao"
	"go_web/models"
	"html/template"
	"log"
)

func SavePost(post *models.Post) {

	dao.SavePost(post)

}

func UpdatePost(post *models.Post) {
	dao.UpdatePost(post)
}

func GetPostDetail(pid int) (*models.PostRes, error) {

	post, err := dao.GetPostDetailByPId(pid)

	if err != nil {
		return nil, err
	}

	categoryName := dao.GetCategoryNameByID(post.CategoryId)
	userName := dao.GetUserNameByID(post.UserId)

	postMore := models.PostMore{
		Pid:          post.Pid,
		Title:        post.Title,
		Slug:         post.Slug,
		Content:      template.HTML(post.Content),
		CategoryId:   post.CategoryId,
		UserId:       post.UserId,
		CreateAt:     models.DateDay(post.CreateAt),
		UpdateAt:     models.DateDay(post.UpdateAt),
		ViewCount:    post.ViewCount,
		CategoryName: categoryName,
		UserName:     userName,
	}

	var postRes = &models.PostRes{
		Viewer:       config.Cfg.Viewer,
		SystemConfig: config.Cfg.System,
		Article:      postMore,
	}

	return postRes, nil

}

func Writing() (models.WritingRes, error) {

	var wr models.WritingRes

	wr.Title = config.Cfg.Viewer.Title
	wr.CdnURL = config.Cfg.System.CdnURL
	categorys, err := dao.GetAllCategory()
	if err != nil {
		log.Println(err)
		return wr, err
	}

	wr.Categorys = categorys
	return wr, nil

}

func SearchPost(condition string) ([]models.SearchResp, error) {

	posts, err := dao.SearchPostByCondition(condition)

	if err != nil {
		return nil, err
	}

	var searchResps []models.SearchResp

	for _, post := range posts {
		searchResps = append(searchResps, models.SearchResp{
			Pid:   post.Pid,
			Title: post.Title,
		})
	}

	return searchResps, err

}
